<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Descripcion de classSesion
 *
 * @author Jonas Reyes
 */
class Sesion {
    //atributos
    private $username;
    private $password;
    private $logueado;
    private $rol;
    private $tiempo_expiracion;
    private $cookie;
    private $UrlFormLogin;
    private $IpCliente;
    private $Referer;
    private $SOCliente;
    

    function __construct($UrlFormLogin="DEFAULT"){
        if ($UrlFormLogin=="DEFAULT") {
            $UrlFormLogin=$_SERVER['PHP_SELF'];
        }
        $this->Start();
        $this->UrlFormLogin=$UrlFormLogin;
        $this->SetSOCliente();
        $this->SetIpCliente();
    }

    function __destruct(){
        
    }

    public function Start(){
        if (session_start()) {
            return true;
        }else {
            Core::MsgError("No se pudo establecer Sesion para el documento actual.");
            return false;
        }
    }

    public function SetUsername($username){
        if ($_SESSION['username']=$this->username=$username) {
            return true;
        }else {
            return false;
        }
    }

    public function GetUsername(){
        return $this->username;
    }
    
    public function SetPassword($password){
        if ($_SESSION['password']=$this->password=$password) {
            return true;
        }else {
            return false;
        }
    }

    public function GetPassword(){
        return $this->password;
    }

    public function SetRol($rol){
        if ($_SESSION['rol']=$this->rol=$rol) {
            return true;
        }else {
            return false;
        }
    }

    public function GetRol(){
        return $this->rol;
    }

    public function SetLogueado($logueado){
        if ($_SESSION['logueado']=$this->logueado=$logueado) {
            return true;
        }else {
            return false;
        }
    }

    public function GetLogueado(){
        return $this->logueado;
    }

    public function SetIpCliente(){
        if ($this->IpCliente=$_SERVER[REMOTE_ADDR]) {
            return true;
        }else {
            return false;
        }
    }

    public function GetIpCliente(){
        return $this->IpCliente;
    }

    public function SetSOCliente(){

        $userAgent = $_SERVER[HTTP_USER_AGENT];
        $userAgent = strtolower ($userAgent);
        if(strpos($userAgent, "windows") !== false)
        {
            $this->SOCliente="Windows";
            return true;
        }
        if(strpos($userAgent, "linux") !== false)
        {
            $this->SOCliente="GNU/Linux";
            return true;
        }
    }
    public function GetSOCliente(){
        return $this->SOCliente;
    }

    public function SetTiempoExpiracion($tiempo){
        if ($this->tiempo_expiracion=$tiempo) {
            return true;
        }else {
            return false;
        }
    }

    public function GetTiempoExpiracion(){
        return $this->tiempo_expiracion;
    }

    public function SearchVar($var){
        if (isset($_SESSION[$var])) {
            return true;
        }else {
            return false;
        }
    }

    public function FormAccess($action="DEFAULT"){
        if ($action=="DEFAULT") {
            $action=$_SERVER['PHP_SELF'];
        }

        $formulario=<<<eof
        <div id="divFormAccess">
        <form action="$action" method="POST" id="FormAccessAdmin" name="FormAccessAdmin" class="FormAcces">
        <div class="marcoImg">
        <img class="imgForm" alt="Validacion de Acceso" src="imagenes/AccesoAdmin.png" />
        </div>
        <span class="spanInputFormAccess">
        <label class="labelFormAccess" for="username">Usuario:</label>
        <input type="text" class="inputFormAccess" id="username" name="username">
        </span>
        <span class="spanInputFormAccess">
        <label class="labelFormAccess" for="password">Contraseña:</label>
        <input type="password" id="password" class="inputFormAccess" name="password">
        </span>
        <input type="hidden" name="accion" value="Validar Usuario">
        <span class="spanInput">
        <input  type="submit" name="submit" value="Acceder" >
        </span>
        </form>
        </div>
eof;
        return $formulario;
    }

    public function EscuchaSesion(){
        if (isset($_REQUEST[logout])) {
            $this->Logout();
            Core::Redirect($this->UrlFormLogin);
            return false;
        }
     
        if (isset($_SESSION['username'])) {
            $this->MenuSesion();
            return true;
        }elseif (isset($_POST['accion'])) {
            // Aqui realizar la consulta con la BD.
            $admin=$_POST['username'];
            $clave=$_POST['password'];
            $bd=new BD();
            $consulta="SELECT * from administradores WHERE username='$admin' AND password=md5('$clave');";
            $bd->Query($consulta);
            $numFilas=$bd->resultado->num_rows;

            if ($numFilas==1) {
                Core::Msg("Bienvenido ".$_POST['username'].", en breves segundos será redireccionado.");
                $this->SetUsername($_POST['username']);
                $this->SetLogueado('si');
                Core::Redirect($this->UrlFormLogin);
                return false;
            }else {
                Core::MsgError("Error, nombre de usuario o contraseña invalidos. Verifique sus datos y vuelva a ingresar.");
                echo $this->FormAccess();
                return false;
            }
            
        }else {
            //Core::Msg("No se ha logueado, no ha enviado Formulario, por lo tanto hay que mostrar Formulario.");
            echo $this->FormAccess();
            return false;
        }
    }

    public function MenuSesion($IMG="imagenes/user_panel.png",$IMG2="imagenes/logout.png"){
        $URLLOCAL=$_SERVER['PHP_SELF'];
        $usuario=$_SESSION['username'];
        $Msg="<b>$usuario</b>";
        $Msg2="Cerrar Sesión";
        if (!Core::ValidarExistencia($IMG)) {
            $IMG="../".$IMG;
        }
        if (!Core::ValidarExistencia($IMG2)) {
            $IMG2="../".$IMG2;
        }
        ?>
<span style="float:right; display:block;padding:1px;
font-size:11px;text-align:left;vertical-align:middle;font-family:helvetica,Arial,FreeSans;width:130px; text-align:left;">
    <img style="display:inline;margin:0 10px 0 0; vertical-align:middle;" src="<?=$IMG;?>" alt="Usuario"></img><?=$Msg;?>
    <br />
    <a href="<?=$URLLOCAL?>?logout=si" style="background-color:#E0EAF8; border:#2F74D0 solid 1px;font-size:11px;">
    <img style="display:inline;margin:0 10px 0 0; vertical-align:middle;border:0px;" src="<?=$IMG2;?>" alt="Logout"></img>[ <?=$Msg2?> ]
    </a>
    <div id="main_container">

<a href="javascript:void(0)" onclick="javascript:chatWith('janedoe')">Chat With Jane Doe</a>

<!-- YOUR BODY HERE -->

</div>
    </span>
<script type="text/javascript" src="resources/js/jquery.js"></script>
<script type="text/javascript" src="resources/js/chat.js"></script>
        <?;
    }

    public function Logout(){
        $_SESSION=array();
        session_destroy();
    }


    // Solo checkea si en la pagina actual se esta logueado o no
    public function CheckLoginPaginas(){
        if (!isset($_SESSION['logueado'])) {
            return false;
        }else {
            return true;
        }
    }

    // Inhabilita el acceso no autorizado a la pogina donde se invoque el metodo
    public function ProtegerPagina($url="DEFAULT"){
        if ($url=="DEFAULT") {
            $url=URL_CONECT_ADMIN;
        }
        if (!$this->CheckLoginPaginas()) {
            Core::Redirect($url);
            return false;
        }
    }



}//Fin de clase
?>